package org.raymond.iworks.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.commons.constants.CommonConstants;
import org.raymond.iworks.commons.utils.SnowFlake;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class TraceFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        long traceId = SnowFlake.generateId();
        String traceIdStr = String.valueOf(traceId);

        MDC.put("tid", traceIdStr);
        ServerHttpRequest newRequest = request.mutate().headers(httpHeaders ->
                httpHeaders.add(CommonConstants.TRACE_ID, traceIdStr))
                .build();
        exchange = exchange.mutate().request(newRequest).build();
        Mono<Void> result = chain.filter(exchange);
        return result;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
